import axios from 'axios'
import { useSettingsStore } from '../stores/modules/settings'
import { useAuthStore } from '../stores/modules/auth'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 60000, // 60秒超时
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.token

    if (token) {
      // 检查 token 是否过期
      if (authStore.isTokenExpired()) {
        authStore.logout()
        return Promise.reject(new Error('Token已过期'))
      }
      config.headers.Authorization = `Bearer ${token}`
    }

    // 在需要API密钥的请求中使用内存中的API密钥
    if (config.url.includes('/chat/message')) {
      const settingsStore = useSettingsStore()
      const apiKey = settingsStore.getApiKey()

      if (apiKey) {
        config.headers['X-API-Key'] = apiKey
      }
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('Received response from:', response.config.url, {
      status: response.status,
      data: response.data
    })
    return response
  },
  error => {
    console.error('Response error:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      data: error.response?.data,
      message: error.message
    })

    // 特殊处理 CSP 错误
    if (error.message.includes('Content Security Policy')) {
      console.error('CSP Error detected. Please check your CSP configuration.')
    }

    const authStore = useAuthStore()

    // 处理 token 过期错误
    if (error.response?.status === 401 || authStore.isTokenExpired()) {
      authStore.logout()
    }

    return Promise.reject(error)
  }
)

export default api
